<template>
    <LayoutWrap class="bill-detail">
        <h2 style="margin: 20px 0;">
            账单信息
            <el-button @click="handleClick" style="margin-left: 6px;" type="text" class="el-icon-edit"></el-button>
        </h2>
        <ul class="edit-bar" style="margin-bottom: 10px">
            <li>
                <el-button :disabled="isLoading || !(isMultSelect || isEdit)" @click="handleOk" type="primary"
                    >确认修改</el-button
                >
            </li>
            <li>
                <el-button :disabled="isLoading" @click="handleClick" type="default">
                    {{ isEdit ? '隐藏修改' : '显示修改' }}
                </el-button>
            </li>
        </ul>
        <el-table
            v-loading="isLoading"
            :data="tableHeads"
            style="width: 100%;max-width: 980px;"
            :border="false"
            :stripe="true"
            :show-header="true"
        >
            <el-table-column prop="name" key="ProjectName" label="ProjectName"> </el-table-column>
            <el-table-column prop="value" key="Value" label="Value">
                <template v-slot="{row}">
                    <template v-if="row.name === '借款平台'">
                        <template v-if="isEdit">
                            <el-select
                                v-model="row.value"
                                :disabled="!isEdit"
                                filterable
                                clearable
                                placeholder="请选择"
                                style="width: 100%"
                            >
                                <el-option
                                    v-for="item in optionsPlatforms"
                                    :key="item._id"
                                    :label="`${item.name}`"
                                    :value="item.id"
                                >
                                </el-option>
                            </el-select>
                        </template>
                        <template v-else>
                            {{ getPlatformValue(row, optionsPlatforms) }}
                        </template>
                    </template>
                    <template v-else-if="!isEdit || row.name === '账单ID'">
                        {{ row.value }}
                    </template>

                    <el-input v-else v-model="row.value" placeholder=""></el-input>
                </template>
            </el-table-column>
            <!-- <el-table-column prop="remark" key="Remark" label="Remark（不会被录入）"> </el-table-column> -->
        </el-table>
        <h2 style="margin: 20px 0 10px 0">
            账单分期信息
            <el-button @click="handleClick" style="margin-left: 6px;" type="text" class="el-icon-edit"></el-button>
        </h2>
        <ul class="edit-bar" style="margin-bottom: 10px">
            <li>
                <el-button :disabled="isLoading || !(isMultSelect || isEdit)" @click="handleOk" type="primary"
                    >确认修改</el-button
                >
            </li>
            <li>
                <el-button :disabled="isLoading" @click="handleClick" type="default">
                    {{ isEdit ? '隐藏修改' : '显示修改' }}
                </el-button>
            </li>
            <li>
                <el-select
                    :disabled="isLoading || !isMultSelect"
                    v-model="multSelectStatus"
                    placeholder="选择还款状态"
                    style="width: 150px;"
                >
                    <el-option label="还款中" :value="BILL_STATUS_REPAYMENT"></el-option>
                    <el-option label="已结清" :value="BILL_STATUS_SETTLED"></el-option>
                    <el-option label="已逾期" :value="BILL_STATUS_PAST_DUE"></el-option>
                </el-select>
            </li>
        </ul>
        <el-table
            v-loading="isLoading"
            :data="tableData"
            @selection-change="handleSelectionChange"
            border
            style="width: 100%"
        >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column prop="stage" key="stage" label="当前期数" :width="isMobile ? 35 : 80"> </el-table-column>
            <el-table-column prop="status" key="row.status" label="状态" :width="60" align="center">
                <template v-slot="{row}">
                    <span :title="row.status | getBillStatusText" :class="row.status | getBillStatusColor"> </span>
                </template>
            </el-table-column>
            <el-table-column prop="date" key="date" label="还款日期">
                <template v-slot="{row}">
                    <template v-if="!isEdit">
                        {{ row.date }}
                    </template>
                    <el-input v-else :disabled="isMultSelect" v-model="row.date" placeholder=""></el-input>
                </template>
            </el-table-column>
            <el-table-column prop="status" key="status" label="账单状态">
                <template v-slot="{row}">
                    <span v-if="!isEdit" :class="row.status | handleGetTheBillClassnameByTotalStatus">
                        {{ row.status | handleGetBillStatusTextByStatus }}
                    </span>
                    <el-select
                        v-else
                        :disabled="isMultSelect"
                        v-model="row.status"
                        placeholder="选择还款状态"
                        style="width: 150px;"
                    >
                        <el-option label="还款中" :value="1"></el-option>
                        <el-option label="已结清" :value="2"></el-option>
                        <el-option label="已逾期" :value="3"></el-option>
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column prop="principal" key="principal" label="本金">
                <template v-slot="{row}">
                    <template v-if="!isEdit">
                        {{ row.principal }}
                    </template>
                    <el-input v-else :disabled="isMultSelect" v-model="row.principal" placeholder=""></el-input>
                </template>
            </el-table-column>
            <el-table-column prop="interest" key="interest" label="利息">
                <template v-slot="{row}">
                    <template v-if="!isEdit">
                        {{ row.interest }}
                    </template>
                    <el-input v-else :disabled="isMultSelect" v-model="row.interest" placeholder=""></el-input>
                </template>
            </el-table-column>
        </el-table>
    </LayoutWrap>
</template>

<script>
import {getBillObjKeys} from '@/views/bill/getObjKeys';
import {getBill, putBillList, getBillPlatforms} from '@/api/bill';
import {BASIC_MONEY, THE_MOMENT_YYMMDD, THE_MOMENT_YYMMDD_HHMMSS} from '@/utils/constant';
import moment from 'moment';
import {handleGetBillStatusTextByStatus, handleGetTheBillClassnameByTotalStatus} from '@/views/bill/filters-bill';
import {deepCopy} from '@/utils/utils';
import {mapState} from 'vuex';
import {keep2decimalPlaces, getBillStatusText, getBillStatusColor} from '@/filters';
import {BILL_STATUS_REPAYMENT, BILL_STATUS_SETTLED, BILL_STATUS_PAST_DUE} from '@/views/bill/constant-bill';
export default {
    name: 'bill-detail',
    filters: {
        getBillStatusColor,
        getBillStatusText,
        handleGetBillStatusTextByStatus,
        handleGetTheBillClassnameByTotalStatus
    },
    data() {
        return {
            tableHeads: [
                {
                    name: '账单ID',
                    value: '',
                    remark: '（创建不填，修改必填）'
                },
                {
                    name: '借款平台',
                    value: '',
                    remark: '必填（招商银行信用卡）'
                },
                {
                    name: '账单名称',
                    value: '',
                    remark: '必填（招商银行信用卡）'
                },
                {
                    name: '借款金额',
                    value: '',
                    remark: '必填（1000.00）'
                },
                {
                    name: '合计需还',
                    value: '',
                    remark: '必填（1000.00）'
                },
                {
                    name: '综合年化费率',
                    value: '',
                    remark: '必填（20 === 20%）'
                },
                {
                    name: '借款时间',
                    value: '',
                    remark: '必填（YYYY/MM/DD）'
                },
                {
                    name: '还款方式',
                    value: '',
                    remark: '选填（自定义,等额本金）'
                },
                {
                    name: '还款银行',
                    value: '',
                    remark: '必填（招商银行1234）'
                },
                {
                    name: '创建时间',
                    value: '',
                    remark: ''
                },

                {
                    name: '备注',
                    value: '',
                    remark: '选填（账单备注）'
                }
            ],
            tableData: new Array(6).fill('').map((c, i) => ({
                stage: i + 1,
                date: '',
                status: '',
                principal: '',
                interest: ''
            })),
            // 编辑账单数据
            dataSouceEdit: {},
            // 查看详情账单数据
            dataSouceDetail: {},
            // 删除账单对话框
            dialogVisible: false,
            // 删除账单对话框 loading
            dialogLoading: false,
            // 当前的账单数据
            currentRow: {},
            // 编辑账单
            billObjKeys: getBillObjKeys(),
            THE_MOMENT_YYMMDD,
            isEdit: false,
            multipleSelection: [],
            multSelectStatus: BILL_STATUS_SETTLED,
            isLoading: false,
            BILL_STATUS_REPAYMENT,
            BILL_STATUS_SETTLED,
            BILL_STATUS_PAST_DUE,
            optionsPlatforms: []
        };
    },
    computed: {
        ...mapState('app', {
            isMobile: state => state.isMobile
        }),
        isMultSelect() {
            return this.multipleSelection.length > 0;
        }
    },
    created() {
        const query = this.$route.query;
        if (query.type === 'detail') {
            this.handleGetBill(query.id);
        }

        this.getBillPlatforms();
    },
    methods: {
        getPlatformValue(row, optionsPlatforms) {
            if (row.value) {
                const result = optionsPlatforms.find(item => item._id === row.value);
                return result ? result.name : '';
            } else {
                return '';
            }
        },
        getBillPlatforms() {
            const newItem = {page: 1, pageSize: 1000, sort: 'date', select: '_id name remark -bills'};
            return getBillPlatforms(newItem)
                .then(({data: res}) => {
                    this.optionsPlatforms = res.data;
                })
                .catch(error => {
                    console.log('error', error);
                });
        },
        handleSelectionChange(value) {
            this.multipleSelection = value;
        },
        handleOk() {
            const isMultSelect = this.isMultSelect;
            const multSelectStatus = this.multSelectStatus;
            const multipleSelection = this.multipleSelection;

            if (isMultSelect && (![1, 2, 3].includes(multSelectStatus) || multipleSelection.length === 0)) {
                return this.$message({type: 'error', message: '请选择状态或要修改的数据'});
            }

            const stages = this.tableData.map(item => {
                if (isMultSelect && multipleSelection.find(c => c._id === item._id)) {
                    return {
                        ...item,
                        date: new Date(item.date),
                        status: multSelectStatus,
                        cash: keep2decimalPlaces(item.principal * BASIC_MONEY) - 0
                    };
                }
                return {
                    ...item,
                    date: new Date(item.date),
                    cash: keep2decimalPlaces(item.principal * BASIC_MONEY) - 0
                };
            });
            const newItem = {...this.dataSouceDetail, stages};

            const billObjKeys = this.billObjKeys;
            this.tableHeads.forEach(item => {
                let value = item.value;
                newItem[billObjKeys[item.name]] = value;
                if (billObjKeys[item.name] === 'bank') {
                    newItem.bank = value.slice(0, -4);
                    newItem.bank_number = value.slice(-4);
                }
            });

            // YYYY/MM/DD 正则匹配
            // eslint-disable-next-line max-len
            const regDate = /^\d{4}\/\d{1,2}\/\d{1,2}$/;
            // https://www.cnblogs.com/hyunbar/p/10083532.html
            // ^(([1-9]{1}\d*)|(0{1}))(\.\d{0,2})?$  保留0，1，2位小数点的字符串
            const regNum = /^(([1-9]{1}\d*)|(0{1}))(\.\d{0,2})?$/;

            if (
                this.tableData.some(
                    i => i.date === '' || !(regDate.test(i.date) && new Date(i.date).toString() !== 'Invalid Date')
                )
            ) {
                this.$message({showClose: true, type: 'error', message: '分期时间格式不正确'});
                return;
            }

            const target = stages.find(
                i =>
                    // eslint-disable-next-line operator-linebreak
                    i.principal === '' ||
                    // eslint-disable-next-line operator-linebreak
                    i.interest === '' ||
                    // eslint-disable-next-line operator-linebreak
                    !regNum.test(i.principal) ||
                    !regNum.test(i.interest)
            );

            if (target) {
                this.$message({showClose: true, type: 'error', message: '分期利息或本金格式不正确'});
                return;
            }

            if (!newItem.name) {
                this.$message({showClose: true, type: 'error', message: '账单名称为空'});
                return;
            }

            if (
                // eslint-disable-next-line operator-linebreak
                !newItem.from_time ||
                !(
                    newItem.from_time && // eslint-disable-line
                    regDate.test(newItem.from_time) && // eslint-disable-line
                    new Date(newItem.from_time).toString() !== 'Invalid Date'
                )
            ) {
                this.$message({showClose: true, type: 'error', message: '借款时间格式不正确'});
                return;
            }

            if (!/^(([1-9]{1}\d*)|(0{1}))(\.\d{0,3})?$/.test(newItem.rate)) {
                this.$message({showClose: true, type: 'error', message: '综合年化费率格式不正确'});
                return;
            }
            if (newItem.bank.length < 1 || !/[0-9]{4}/.test(newItem.bank_number)) {
                this.$message({showClose: true, type: 'error', message: '还款银行格式不正确'});
                return;
            }

            if (!regNum.test(newItem.total)) {
                this.$message({showClose: true, type: 'error', message: '借款金额格式不正确'});
                return;
            }
            if (!regNum.test(newItem.total_all)) {
                this.$message({showClose: true, type: 'error', message: '合计需还格式不正确'});
                return;
            }
            newItem.rate = newItem.rate - 0;
            newItem.from_time = new Date(newItem.from_time);
            newItem.total = keep2decimalPlaces(newItem.total * BASIC_MONEY) - 0;
            newItem.total_all = keep2decimalPlaces(newItem.total_all * BASIC_MONEY) - 0;
            this.handlePutBill(newItem);
        },
        handleClick() {
            this.isEdit = !this.isEdit;

            if (!this.isEdit) {
                this.tableData = deepCopy(this.dataSouceDetail.stages) || [];
            }
        },
        // 更新
        handlePutBill(newBill) {
            this.isLoading = true;
            putBillList(newBill._id, newBill)
                .then(({data: res}) => {
                    if (res.status === 204) {
                        this.$message({showClose: true, type: 'success', message: '更新账单成功'});
                    } else {
                        throw new Error(res);
                    }
                })
                .catch(error => {
                    console.error(error);
                    this.$message({type: 'error', message: '更新账单失败'});
                })
                .finally(() => {
                    this.isLoading = false;
                    this.handleGetBill(newBill._id);
                });
        },
        // 获取单条账单信息
        handleGetBill(rowId) {
            this.isLoading = true;
            getBill(rowId)
                .then(({data: res}) => {
                    if (res.status === 200) {
                        const newBill = {
                            ...res.data
                        };
                        newBill.total = keep2decimalPlaces(newBill.total / BASIC_MONEY) - 0;
                        newBill.total_all = keep2decimalPlaces(newBill.total_all / BASIC_MONEY) - 0;

                        newBill.stages = newBill.stages.map(item => {
                            return {
                                ...item,
                                principal: keep2decimalPlaces(item.cash / BASIC_MONEY) - 0,
                                interest: 0,
                                date: moment(item.date).format(THE_MOMENT_YYMMDD),
                                cash: keep2decimalPlaces(item.cash / BASIC_MONEY) - 0
                            };
                        });

                        this.tableData = deepCopy(newBill.stages);

                        const billObjKeys = this.billObjKeys;
                        this.tableHeads = this.tableHeads.map(item => {
                            let value = newBill[billObjKeys[item.name]];
                            if (billObjKeys[item.name] === 'create_date') {
                                value = moment(value).format(THE_MOMENT_YYMMDD_HHMMSS);
                            }
                            if (billObjKeys[item.name] === 'platform') {
                                value = value ? value._id : '';
                            }
                            if (billObjKeys[item.name] === 'from_time') {
                                value = moment(value).format(THE_MOMENT_YYMMDD);
                            }
                            if (billObjKeys[item.name] === 'bank') {
                                value = `${newBill.bank}${newBill.bank_number}`;
                            }
                            const newItem = {...item, value};
                            return newItem;
                        });

                        this.dataSouceDetail = newBill;
                    } else {
                        this.$message({showClose: true, type: 'errors', message: res});
                        throw new Error(res);
                    }
                })
                .catch(error => {
                    this.$message({type: 'error', message: error});
                })
                .finally(() => (this.isLoading = false));
        }
    }
};
</script>

<style lang="scss" scoped>
.bill-detail {
}
.edit-bar {
    display: flex;
    flex-flow: row wrap;
    & > li + li {
        margin-left: 16px;
    }
}
</style>
